package com.stary.music.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * http/https请求工具类
 * @author Stary
 * @version 1.0.0
 */
public class HTTPUtils {
	//日志
	private static final Logger logger=LoggerFactory.getLogger(HTTPUtils.class);
	/**
	 * post提交
	 * @param url 接口地址
	 * @param params 接收的参数字符串
	 * @return 返回结果
	 */
	public static String sendPost(String url, String params) {
		String result = "";		
		try {
			URL u0 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
			conn.setRequestMethod("POST");
			byte contentbyte[] = params.toString().getBytes();
			//设置请求类型
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			//设置表单长度
			conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
			//设置默认语言
			conn.setRequestProperty("Content-Language", "en-US");//zh-CN代表中国  默认为美式英语
			//连接主机的超时时间（单位：毫秒）
			conn.setConnectTimeout(60000);
			//从主机读取数据的超时时间（单位：毫秒)
			conn.setReadTimeout(60000);
			// Post 请求不能使用缓存
			conn.setUseCaches(false);
			// 设置是否从httpUrlConnection读入，默认情况下是true;  
			conn.setDoInput(true);
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在    2 
			// http正文内，因此需要设为true, 默认情况下是false;  
			conn.setDoOutput(true);			
			OutputStream outputStream = conn.getOutputStream();  
			outputStream.write(params.getBytes("UTF-8"));  
			outputStream.close();  
			// 调用HttpURLConnection连接对象的getInputStream()函数,   
			// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
			InputStream in = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(in, "utf-8");  
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
			StringBuffer buffer = new StringBuffer();
			String str="";
			while ((str = bufferedReader.readLine()) != null) {  
				buffer.append(str);  
			}  
			bufferedReader.close();  
			inputStreamReader.close();  
			in.close();  
			conn=null;
			result = buffer.toString();
		} catch (Exception e) {
			logger.error("发送POST请求出现异常!", e);
		}
		return result;
	}
	/**
	 * post提交
	 * @param url 接口地址
	 * @param params 接收的参数字符串
	 * @return 返回结果
	 */
	public static String sendPost(String url,Map<String, String> headerMap, String params) {
		String result = "";		
		try {
			URL u0 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
			conn.setRequestMethod("POST");
			byte contentbyte[] = params.toString().getBytes();
			//设置请求类型
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			//设置表单长度
			conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
			//设置默认语言
			conn.setRequestProperty("Content-Language", "en-US");//zh-CN代表中国  默认为美式英语
			for (String key : headerMap.keySet()) {
				conn.setRequestProperty(key, headerMap.get(key));
			}	
			//连接主机的超时时间（单位：毫秒）
			conn.setConnectTimeout(60000);
			//从主机读取数据的超时时间（单位：毫秒)
			conn.setReadTimeout(60000);
			// Post 请求不能使用缓存
			conn.setUseCaches(false);
			// 设置是否从httpUrlConnection读入，默认情况下是true;  
			conn.setDoInput(true);
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在    2 
			// http正文内，因此需要设为true, 默认情况下是false;  
			conn.setDoOutput(true);			
			OutputStream outputStream = conn.getOutputStream();  
			outputStream.write(params.getBytes("UTF-8"));  
			outputStream.close();  
			// 调用HttpURLConnection连接对象的getInputStream()函数,   
			// 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
			InputStream in = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(in, "utf-8");  
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
			StringBuffer buffer = new StringBuffer();
			String str="";
			while ((str = bufferedReader.readLine()) != null) {  
				buffer.append(str);  
			}  
			bufferedReader.close();  
			inputStreamReader.close();  
			in.close();  
			conn=null;
			result = buffer.toString();
		} catch (Exception e) {
			logger.error("发送POST请求出现异常!", e);
		}
		return result;
	}

	/**
	 * get 提交
	 * @param url 接口地址
	 * @param params 接收的参数字符串
	 */
	public static String sendGet(String url, String params) {
		String result = "";		
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + params;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			//			Map<String, List<String>> map = connection.getHeaderFields();
			//			// 遍历所有的响应头字段
			//			for (String key : map.keySet()) {
			//				logger.debug("{}--->{}",key,map.get(key));
			//			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}           
			result = new String(result.getBytes(),"UTF8");
		} catch (Exception e) {
			logger.error("发送GET请求出现异常！", e);
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}
	/**
	 * get 提交
	 * @param url 接口地址
	 * @param headerMap 请求头
	 * @param params 接收的参数字符串
	 */
	public static String sendGet(String url,Map<String, String> headerMap, String params) {
		String result = "";		
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + params;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			for (String key : headerMap.keySet()) {
				connection.setRequestProperty(key, headerMap.get(key));
			}				

			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			//			Map<String, List<String>> map = connection.getHeaderFields();
			//			// 遍历所有的响应头字段
			//			for (String key : map.keySet()) {
			//				logger.debug("{}--->{}",key,map.get(key));
			//			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}           
			result = new String(result.getBytes(),"UTF8");
		} catch (Exception e) {
			logger.error("发送GET请求出现异常！", e);
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

}

